//
//  PTBluetoothManager.swift
//  PointTest28
//
//  Created by sc-chen on 2023/6/28.
//

import Foundation
import CoreBluetooth

class PTBluetoothManager: NSObject, ObservableObject, CBCentralManagerDelegate {
    private var centralManager: CBCentralManager!
    private var p_self: CBPeripheral!
    
    @Published var isBluetoothOn = false
    @Published var status = ""
    
    override init() {
        super.init()
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            isBluetoothOn = true
            startScanning()
        } else {
            isBluetoothOn = false
        }
    }
    
    // 开始扫描外设
    func startScanning() {
        centralManager.scanForPeripherals(withServices: nil, options: nil)
    }
    
    // 发现外设后的回调
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi: NSNumber) {
        // 根据你的需求判断是否为指定外设
        if peripheral.name == "YourDeviceName" {
            //self.peripheral = peripheral
            centralManager.connect(peripheral, options: nil)
        }
        
        if peripheral.name != nil {
            print("发现外设:\(peripheral)")
        }
    }
    
    // 连接外设后的回调
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        // 可以在这里处理连接成功后的操作，比如发现外设的服务和特征
        print("连接外设成功")
        status = "蓝牙连接成功"
        centralManager.stopScan()
    }
    
    // 连接外设失败的回调
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        // 连接失败处理
        print("连接外设失败的回调")
        status = "蓝牙连接失败"
    }
    
    // 断开外设连接的回调
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        // 外设断开连接处理
        print("断开外设连接的回调")
        status = "蓝牙断开"
    }
    
    func startPaired(uid: String) {
        //let uuid = UUID(uuidString: "3C54DFA6-262D-CCDF-1677-69E492BAD8B4")
        if let uuid = UUID(uuidString: uid) {
            let uuids: [UUID] = [uuid]
            let peripheral = centralManager.retrievePeripherals(withIdentifiers: uuids).first
            if let p = peripheral {
                p_self = p
                centralManager.connect(p_self)
            }
        }else{
            status = "请输入有效的蓝牙mac地址"
            DispatchQueue.main.asyncAfter(deadline: .now()+3){
                self.status = ""
            }
        }
    }
    
    func endPaired() {
        if let p = p_self{
            centralManager.cancelPeripheralConnection(p)
            startScanning()
        }
    }
}
